package com.cds.drizzt.dao;

import com.cds.drizzt.entity.Users;
import com.cds.drizzt.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
@Slf4j
public class UsersDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    /**
     * 插入用户信息
     * @param users
     */
    public void insert(Users users) {
        String sql = "INSERT INTO user (id, name, username, password, createtime, updatetime, del_flag) VALUES (?, ?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(
                sql,
                snowflakeIdGenerator.nextId(),
                users.getName(),
                users.getUsername(),
                users.getPassword(),
                LocalDateTime.now(),
                LocalDateTime.now(),
                0
        );
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    public Users getUserByUsername(String username) {
        String sql = "select * from user where username = ?";
        List<Users> usersList = jdbcTemplate.query(
            sql,
            (rs, rowNum) ->
            new Users(
                rs.getLong("id"),
                rs.getString("name"),
                rs.getString("username"),
                rs.getString("password"),
                rs.getTimestamp("createtime").toLocalDateTime() != null ? rs.getTimestamp("createtime").toLocalDateTime() : null,
                rs.getTimestamp("updatetime").toLocalDateTime() != null ? rs.getTimestamp("updatetime").toLocalDateTime() : null,
//                rs.getLocalDateTime("createtime"),   因为jdbc没有支持getLocalDateTime，所以用上面的方法转换
//                rs.getLocalDateTime("updatetime"),
                rs.getInt("del_flag")
            ),
            username
        );
        // 如果用户列表为空，返回空的Optional对象；否则，返回用户列表的第一个元素
        Optional<Users> usersOptional = usersList.isEmpty() ? Optional.empty() : Optional.of(usersList.get(0));
        // 如果Optional对象包含用户信息，返回用户信息；否则，返回null
        return usersOptional.orElse(null);
    }
}
